package cn.itcast.crm.service.impl;

import cn.itcast.crm.dao.CustomerRepository;
import cn.itcast.crm.domain.Customer;
import cn.itcast.crm.service.CustomerService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class CustomerServiceImpl implements CustomerService {
    @Autowired
    private CustomerRepository customerRepository;

    //查询所有未关联customer
    @Override
    public List<Customer> findNoAssociationCustomers() {

        return customerRepository.findByFixedAreaIdIsNull();
    }

    //查询所有已关联customer
    @Override
    public List<Customer> findHasAssociationCustomers(String fixedArea) {
        return customerRepository.findByFixedAreaId(fixedArea);
    }

    //将指定customer关联到指定fixedarea
    @Override
    @Transactional
    public void associationCustomerToFixedArea(String customerIdStr, String fixedAreaId) {
        //先取消关联 在根据id进行关联 即可实现解除关联
        customerRepository.clearFixedAreaId(fixedAreaId);
        //对传入customerIdStr进行非空判断
        if (StringUtils.isBlank(customerIdStr) || "null".equals(customerIdStr)) {
            return;
        }

        //数据处理 将customerid 切割 返回id数组
        String[] customerIdArray = customerIdStr.split(",");
        for (String customerId : customerIdArray) {
            Integer id = Integer.parseInt(customerId);
            customerRepository.updateFixedAreaId(fixedAreaId, id);
        }


    }

    //注册顾客信息
    @Override
    public void regist(Customer customer) {
        customerRepository.save(customer);
    }

    @Override
    public Customer findByTelephone(String telephone) {
        return customerRepository.findByTelephone(telephone);
    }

    @Override
    public void updateType(String telephone) {
        customerRepository.updateType(telephone);

    }

    @Override
    public Customer login(String telephone, String password) {

        return customerRepository.findByTelephoneAndPassword(telephone,password);
    }

    @Override
    //根据address查询fixedareaId
    public String findFixedAreaIdByAddress(String address) {
        return customerRepository.findFixedAreaIdByAddress(address);
    }
}
